package com.ljfiction.book.activitys;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.ljfiction.book.Baner.MyBookBean;
import com.ljfiction.book.Baner.ReadAidsametimeBook;
import com.ljfiction.book.Dialog.AuthorAidTishiDialog;
import com.ljfiction.book.Dialog.NoBackgLodDialog;
import com.ljfiction.book.Dialog.YinzhangImageDialog;
import com.ljfiction.book.MyView.DividerItemDecoration;
import com.ljfiction.book.R;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.tools.ScreenUtils;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.ShareTool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.BaseRequest;
import com.zhy.autolayout.utils.AutoUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import okhttp3.Call;
import okhttp3.Response;


public class ReaderAidActivity extends BaseActivity {

    @BindView(R.id.aidbookimage)
    ImageView aidbookimage;
    @BindView(R.id.yingyuanbookname)
    TextView yingyuanbookname;
    @BindView(R.id.yingyuannum)
    TextView yingyuannum;
    @BindView(R.id.yingyuanrecycle)
    RecyclerView yingyuanrecycle;
    @BindView(R.id.yingyuanxialaimage)
    ImageView yingyuanxialaimage;
    private BaseQuickAdapter samePeriodadapter;
    private PopupWindow popupWindow;
    private List<MyBookBean.DataBean> booklist = new ArrayList<>();
    private List<ReadAidsametimeBook.DataBean.SamePeriodSupportInfoBean> samePeriodBooklist = new ArrayList<>();

    private NoBackgLodDialog noBackgLodDialog;
    private boolean isxlala = true;
    private String bookImage = "";
    private String bookName = "";
    private int bookId1;
    private YinzhangImageDialog yinzhangImageDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reader_aid);
        ButterKnife.bind(this);
        bookId1 = SettingManager.getInstance().getNewUpdateBookId();
        intAllBookdata();
        intsameView();
    }

    private void intsameView() {
        yingyuanrecycle.setLayoutManager(new GridLayoutManager(this, 3));
        yingyuanrecycle.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        yingyuanrecycle.setAdapter(samePeriodadapter = new BaseQuickAdapter<ReadAidsametimeBook.DataBean.SamePeriodSupportInfoBean, BaseViewHolder>(R.layout.aidsame_item, samePeriodBooklist) {
            @Override
            protected void convert(BaseViewHolder helper, ReadAidsametimeBook.DataBean.SamePeriodSupportInfoBean item) {
                AutoUtils.autoSize(helper.itemView);
                helper.setText(R.id.aidsamebookname, item.getBookName());
                helper.setText(R.id.aidsamnum, "应援人数 " + item.getIntegralnum());
                Glide.with(mContext).load(item.getBookImage()).bitmapTransform(new RoundedCornersTransformation(mContext, 10, 1)).into((ImageView) helper.getView(R.id.aidsame_bookimage));
            }
        });
        if (UserManageBean.isLogin()&&SettingManager.getInstance().getIsFirstAid(UserManageBean.userBean.getUserId())){
         new AuthorAidTishiDialog(this);
            SettingManager.getInstance().savetIsFirstAid(UserManageBean.userBean.getUserId());
        }
    }

    private void intAllBookdata() {
        OkHttpUtils.post(HttpManager.IP + "/book-AuthorAllBookInfo")
                .headers("token", "0")
                .params("authorId", String.valueOf(UserManageBean.userBean.getUserId()))
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        if (noBackgLodDialog == null) {
                            noBackgLodDialog = new NoBackgLodDialog(ReaderAidActivity.this, true);
                        }
                        noBackgLodDialog.show();
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (noBackgLodDialog != null) {
                            noBackgLodDialog.dismis();
                        }
                        try {
                            Gson gson = new Gson();
                            MyBookBean bookbean = gson.fromJson(s, MyBookBean.class);
                            if (bookbean.getReturnCode() == 200) {
                                booklist.addAll(bookbean.getData());
                                if (booklist.size() < 1) {
                                    showToast("您还未有已审核通过的书！");
                                    goBack();
                                } else {

                                    if (bookId1 == 0) {
                                        bookId1 = booklist.get(0).getBookId();
                                    } else {
                                        for (MyBookBean.DataBean ss :
                                                booklist) {
                                            if (ss.getBookId() == bookId1) {
                                                bookImage = ss.getBookImage();
                                                bookName = ss.getBookName();
                                                intView();
                                            }
                                        }
                                    }
                                    intData(String.valueOf(bookId1));
                                }
                            } else {
                                showToast("您还未有已审核通过的书！");
                                goBack();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void intData(String bookId) {
        OkHttpUtils.post(HttpManager.IP + "/getBookSupportInfo")

                .params("bookId", bookId)
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        if (noBackgLodDialog == null) {
                            noBackgLodDialog = new NoBackgLodDialog(ReaderAidActivity.this, true);
                        }
                        noBackgLodDialog.show();
                    }

                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (noBackgLodDialog != null) {
                            noBackgLodDialog.dismis();
                        }
                        try {
                            Gson gson = new Gson();
                            ReadAidsametimeBook readAidsametimeBook = gson.fromJson(s, ReadAidsametimeBook.class);
                            if (readAidsametimeBook.getReturnCode() == 200) {
                                yingyuannum.setText("本书应援 " + readAidsametimeBook.getData().getSupportNum());
                                bookImage = readAidsametimeBook.getData().getBookCover();
                                bookName = readAidsametimeBook.getData().getBookName();
                                intView();
                                samePeriodBooklist.clear();
                                samePeriodBooklist.addAll(readAidsametimeBook.getData().getSamePeriodSupportInfo());
                                samePeriodadapter.notifyDataSetChanged();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void intView() {
        Glide.with(this).load(bookImage).bitmapTransform(new RoundedCornersTransformation(this, 10, 1)).into(aidbookimage);

        yingyuanbookname.setText(bookName);

    }

    @OnClick({R.id.yingyuanback, R.id.yingyuanguize, R.id.yingyuanallbook, R.id.yingyuanzhaohuan,R.id.yinzhang})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.yingyuanback:
                goBack();
                break;
            case R.id.yingyuanguize:
                Intent intent = new Intent(ReaderAidActivity.this, AidGuizeActivity.class);
                startActivity(intent);
                break;

            case R.id.yingyuanallbook:
                if (popupWindow != null && !popupWindow.isShowing()) {
                    popupWindow.showAsDropDown(yingyuanxialaimage);
                } else {
                    showPopuWindow();
                }

                yingyuanxialaimage.setImageResource(isxlala ? R.mipmap.yingyuanshangla : R.mipmap.yingyuanxiala);
                isxlala = !isxlala;
                break;
            case R.id.yingyuanzhaohuan:
                ShareTool.toSharexiaochengxu(String.valueOf(bookId1), bookName, bookImage);
                break;
            case R.id.yinzhang:
                if (yinzhangImageDialog==null){
                    yinzhangImageDialog = new YinzhangImageDialog(ReaderAidActivity.this);
                }
                yinzhangImageDialog.show();

                break;
        }
    }

    private void showPopuWindow() {
        @SuppressLint("InflateParams") View contentView = LayoutInflater.from(this).inflate(R.layout.read_aidallbook, null);
        RecyclerView recyclerView = contentView.findViewById(R.id.readaidallbookrecycle);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        BaseQuickAdapter allBookadapter;
        recyclerView.setAdapter(allBookadapter = new BaseQuickAdapter<MyBookBean.DataBean, BaseViewHolder>(R.layout.aidallbook_item, booklist) {
            @Override
            protected void convert(BaseViewHolder helper, MyBookBean.DataBean item) {
                AutoUtils.autoSize(helper.itemView);
                bookImage = item.getBookImage();
                helper.setText(R.id.aidallbookname, item.getBookName());
            }
        });
        allBookadapter.setOnItemClickListener((adapter, view, position) -> {
            bookId1 = booklist.get(position).getBookId();
            intData(String.valueOf(bookId1));
            yingyuanbookname.setText(booklist.get(position).getBookName());
            Glide.with(ReaderAidActivity.this).load(booklist.get(position).getBookImage()).bitmapTransform(new RoundedCornersTransformation(ReaderAidActivity.this, 10, 1)).into(aidbookimage);
            if (booklist.get(position).getBookCheckStatus()!=0){
                SettingManager.getInstance().saveNewUpdateBookId(booklist.get(position).getBookId());
            }
        });
        popupWindow = new PopupWindow(contentView);
        //使其聚集
        popupWindow.setFocusable(true);
        // 设置允许在外点击消失
        popupWindow.setOutsideTouchable(true);
        //这个是为了点击“返回Back”也能使其消失，并且并不会影响背景
        popupWindow.setBackgroundDrawable(new BitmapDrawable(getResources()));
        // 设置SelectPicPopupWindow弹出窗体的宽
        popupWindow.setWidth(ScreenUtils.getScreenWidth() / 3);
        if (booklist.size() > 6) {
            popupWindow.setHeight(ScreenUtils.getScreenHeight() / 4);
        } else {
            popupWindow.setHeight(ScreenUtils.getNum(this, booklist.size() * 40));
        }
        // 设置SelectPicPopupWindow弹出窗体动画效果
        // popupWindow.setAnimationStyle(R.style.AnimBottom);
        //popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.back_search_img));
        popupWindow.showAsDropDown(yingyuanxialaimage);
    }
}
